﻿using System;
using System.Data;
using System.Data.Objects;
using Microsoft.SqlServer.Management;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Data.SqlClient;
using System.Data.Metadata.Edm;
using QuanLyKho.Server;


namespace QuanLyKho.Server.BLL
{
    public class CauHinhBLL
    {
        Microsoft.SqlServer.Management.Smo.Server server;
        public CauHinhBLL()
        {
            using (QuanLyKhoEntities entities = new QuanLyKhoEntities(QuanLyKhoServerGlobal.ConnectionString)) ;
        }

        //public bool CheckExistingDatabase()
        //{
        //    using (QuanLyKhoEntities entities = new QuanLyKhoEntities(QuanLyKhoServerGlobal.ConnectionString))
        //    {
        //        bool DataExists = false;
        //        if (!entities.Database.Exists() == true)
        //        {
        //            DataExists = false;
        //        }
        //        else
        //        {
        //            DataExists = true;
        //        }
        //        return DataExists;
        //    }
        //}
        
        /// <summary>
        /// Backup db
        /// </summary>
        /// <param name="path"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
       
        public string BackupDatabase(String databaseName, String userName,String password, String serverName, String destinationPath)
        {
            // tên file name sẽ trả về
            string fileName = string.Empty;

            ServerConnection conn = new ServerConnection(serverName, userName, password);
            server = new Microsoft.SqlServer.Management.Smo.Server(conn);
            Backup backupMgr = new Backup();
            DateTime ngaygio = DateTime.Now;
            fileName = "QuanLyKho_" + ngaygio.Year
                                    + String.Format("{0:00}", ngaygio.Month)
                                    + String.Format("{0:00}", ngaygio.Day)
                                    + String.Format("{0:00}", ngaygio.Hour)
                                    + String.Format("{0:00}", ngaygio.Minute)
                                    + String.Format("{0:00}", ngaygio.Second)
                                    + ".bak";
            backupMgr.Devices.AddDevice(destinationPath + @"\" + fileName, DeviceType.File);
            backupMgr.Database = databaseName;
            backupMgr.Action = BackupActionType.Database;
            backupMgr.SqlBackup(server);
            return fileName;
        }
        

        public void RestoreDatabase(string databaseName, string filePath,
                                       string serverName, string userName, string password)
        {
            // Create a new connection to the selected server name
            ServerConnection srvConn = new ServerConnection(serverName, userName, password);
            // Log in using SQL authentication instead of Windows authentication
            srvConn.LoginSecure = false;

            // Kill all connection of database is using
            server = new Microsoft.SqlServer.Management.Smo.Server(srvConn);
            server.KillAllProcesses(databaseName);

            // Create a new SQL Server object using the connection we created
            server = new Microsoft.SqlServer.Management.Smo.Server(srvConn);

            // If the user has chosen the file from which he wants the database to be restored
            if (server != null)
            {
                // Create a new database restore operation
                Backup bckDatabase = new Backup();
                Restore rstDatabase = new Restore();
                // Set the restore type to a database restore
                rstDatabase.Action = RestoreActionType.Database;
                bckDatabase.Action = BackupActionType.Database;
                // Overwrite DB when db is existing
                rstDatabase.ReplaceDatabase = true;
                // Set the database that we want to perform the restore on
                rstDatabase.Database = databaseName;
                // Set the backup device from which we want to restore, to a file
                string[] str = new string[1];
                str[0] = @"\";
                string fileName = filePath.Split(str, StringSplitOptions.None)[filePath.Split(str, StringSplitOptions.None).Length - 1];
                BackupDeviceItem bkpDevice = new BackupDeviceItem(filePath, DeviceType.File);
                // Add the backup device to the restore type
                rstDatabase.Devices.Add(bkpDevice);
                // If the database already exists, replace it
                rstDatabase.ReplaceDatabase = true;
                // Perform the restore
                rstDatabase.SqlRestore(server);
            }
        }

      
    }
}
